package com.xzy.generic.plus;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;

/**
 * @author xzy.xiao
 * @date 2023/3/13  15:39
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class GenericEventPublisher implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        GenericEventPublisher.applicationContext = applicationContext;
    }

    public static void sendEvent(ApplicationEvent applicationEvent) {
        if (applicationContext != null) {
            applicationContext.publishEvent(applicationEvent);
        }
    }

    public static <T> void sendGenericEvent(Object source, T eventData) {
        if (applicationContext != null) {
            applicationContext.publishEvent(new GenericEvent<>(source, eventData));
        }
    }
}